package cn.stylefeng.guns.modular.yingbao.service.impl;
import	java.rmi.RemoteException;
import	java.sql.ResultSet;
import	java.nio.file.attribute.UserPrincipal;
import java.util.*;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.yingbao.entity.*;
import cn.stylefeng.guns.modular.yingbao.handler.SysSellHandler;
import cn.stylefeng.guns.modular.yingbao.mapper.SysSellMapper;
import cn.stylefeng.guns.modular.yingbao.mapper.UserBankMapper;
import cn.stylefeng.guns.modular.yingbao.mapper.UserMoneyMapper;
import cn.stylefeng.guns.modular.yingbao.mapper.UserPayMapper;
import cn.stylefeng.guns.modular.yingbao.model.params.SysSellLogParam;
import cn.stylefeng.guns.modular.yingbao.model.params.SysSellParam;
import cn.stylefeng.guns.modular.yingbao.model.result.SysSellResult;
import cn.stylefeng.guns.modular.yingbao.service.*;
import cn.stylefeng.guns.modular.yingbao.util.DateUtils;
import cn.stylefeng.guns.modular.yingbao.util.RandomNum;
import cn.stylefeng.guns.modular.yingbao.util.StringUtil;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;

/**
 * <p>
 * 挂售 服务实现类
 * </p>
 *
 * @author jj
 * @since 2019-12-11
 */
@Slf4j
@Service
public class SysSellServiceImpl extends ServiceImpl<SysSellMapper, SysSell> implements SysSellService {
    @Autowired
    SysSellLogService sysSellLogService;

    @Autowired
    SysSellHandler sysSellHandler;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    UserMoneyService userMoneyService;

    @Autowired
    UserMoneyLogService userMoneyLogService;

    @Autowired
    UserMoneySettingService userMoneySettingService;

    @Autowired
    UserPayService userPayService;

    @Autowired
    ContractSettingService contractSettingService;

    @Autowired
    SysRebateSettingService sysRebateSettingService;

    @Autowired
    SysSellSettingService sysSellSettingService;

    @Autowired
    SysRebateService sysRebateService;
    @Autowired
    PayeeService payeeService;
    @Autowired
    UserBankMapper userBankMapper;

    @Override
    @Transactional(rollbackFor = Exception.class,timeout = 360)
    public ResponseData add(SysSellParam param){
        SysSell entity = getEntity(param);
        if (!"1".equals(entity.getStandby1())){
            return ResponseData.error("参数错误");
        }
        Long price = entity.getPrice()*100;
        ContractSetting one = contractSettingService.getOne(new QueryWrapper<ContractSetting>().le("price",price).ge("price1",price).eq("contract_type",entity.getContractType()));
        if (one ==null){
            return ResponseData.error("不可低于或者高于合约区间");
        }
        sysSellHandler.batchInsert(entity, one);
        return ResponseData.success();

    }

    @Override
    @Transactional(rollbackFor = Exception.class,timeout = 360)
    public ResponseData appAddItem(SysSellParam sysSellParam) {
        SysSell entity = getEntity(sysSellParam);
        Long money=0L;
        Long buyerUserid = entity.getBuyerUserid();
        Integer payType = entity.getPayType();
        if (buyerUserid==null){
            return ResponseData.error("卖家id为空！");
        }
        if (payType==null){
            return ResponseData.error("参数错误！");
        }
        UserMoneySetting userMoneySetting = userMoneySettingService.getOne(null);

        SysUser user = sysUserService.getById(buyerUserid);
        if (user == null){
            return ResponseData.error("没有该用户");
        }
        ResponseData active = isActive(user);
        if (active != null){
            return active;
        }
        if ("1".equals(user.getBackup3())) {
            return ResponseData.error("该账户不可挂售！请联系客服");
        }
        Long price = entity.getPrice()*100;
        List<ContractSetting> list = contractSettingService.list(new QueryWrapper<ContractSetting>()
                .le("price", price).ge("price1", price).in("contract_type", 1, 2, 3).orderByAsc("price1"));
        if (list ==null||list.size()<1){
            return ResponseData.error("不可低于或者高于合约区间");
        }
        ContractSetting one = list.get(0);
        UserMoney userMoney=new UserMoney();
        UserMoney um = userMoney.selectOne(new QueryWrapper<UserMoney>().eq("userid",buyerUserid));
        if (um==null){
            return ResponseData.error("没有该卖家");
        }

        if (payType==0){

            if (userMoneySetting.getMinAvailSetting()>price){
                return ResponseData.error("不可低于最低可用挂售金额！");
            }

            if (um.getAvailMoney()<price){
                return ResponseData.error("不可超出可用余额！");
            }
            List<SysSell> list1 = this.list(new QueryWrapper<SysSell>().eq("buyer_userid", entity.getBuyerUserid())
                    .eq("pay_type", payType).between("create_time",initDateByDay(),new Date()));

            if (list1!= null||list1.size()>0){
                Long sum = list1.stream().mapToLong(SysSell::getPrice).sum();
                if (userMoneySetting.getMaxAvailSetting()<sum+price){
                    return ResponseData.error("可用余额挂售已达上限！");
                }
            }
            money=um.getAvailMoney()-price;
            um.setAvailMoney(money);
        }
        if (payType==1){
            if (um.getExpandMoney()<price){
                return ResponseData.error("不可超出团队返利余额！");
            }

            if (userMoneySetting.getMinExpandSetting()>price){
                return ResponseData.error("不可低于最低团队挂售金额！");
            }

            List<SysSell> list1 = this.list(new QueryWrapper<SysSell>().eq("buyer_userid", entity.getBuyerUserid())
                    .eq("pay_type", payType).between("create_time",initDateByDay(),new Date()));

            if (list1!= null||list1.size()>0){
                Long sum = list1.stream().mapToLong(SysSell::getPrice).sum();
                if (userMoneySetting.getMaxExpandSetting()<sum+price){
                    return ResponseData.error("可用余额挂售已达上限！");
                }
            }
            money=um.getExpandMoney()-price;
            um.setExpandMoney(money);
        }
        if (payType==2){
            if (um.getRebateMoney()<price){
                return ResponseData.error("不可超出推广余额！");
            }

            if (userMoneySetting.getMinRebateSetting()>price){
                return ResponseData.error("不可低于最低推广挂售金额！");
            }

            List<SysSell> list1 = this.list(new QueryWrapper<SysSell>().eq("buyer_userid", entity.getBuyerUserid())
                    .eq("pay_type", payType).between("create_time",initDateByDay(),new Date()));

            if (list1!= null||list1.size()>0){
                Long sum = list1.stream().mapToLong(SysSell::getPrice).sum();
                if (userMoneySetting.getMaxRebateSetting()<sum+price){
                    return ResponseData.error("可用余额挂售已达上限！");
                }
            }
            money=um.getRebateMoney()-price;
            um.setRebateMoney(money);
        }
        boolean b = um.updateById();
        if (!b){
            return ResponseData.error("金额更新错误！");
        }
        entity.setPrice(price);
        entity.setContractType(one.getContractType());
        entity.setStuats("1");
        entity.setVersion(0);
        entity.setOrdinal(RandomNum.getUUID_16());
        entity.setCreateTime(new Date());
        entity.setStandby1("0");

        List<UserPay> payList = queryAll(buyerUserid);
        if(payList.size() == 0 || payList == null) {
            return ResponseData.error("暂无收账信息");
        }
        payList.forEach(m -> {
            if(m.getPayid() == 3){
                m.setBackup1(m.getBank());
            }
        });
        String pay = JSONObject.toJSONString(payList);
        entity.setSellDetails(pay);
        boolean save = this.save(entity);
        if (save){
            SysSellLogParam sysSellLog=new SysSellLogParam();
            ToolUtil.copyProperties(entity, sysSellLog);
            sysSellLog.setUserid(entity.getBuyerUserid());
            sysSellLog.setStandby3("挂售订单！");
            sysSellLogService.add(sysSellLog);

        }else {
            throw new UnsupportedOperationException("错误！");
        }
        UserMoneyLog userMoneyLog =new UserMoneyLog();
        userMoneyLog.setCreateTime(new Date());
        userMoneyLog.setMoney(-price);
        userMoneyLog.setUserid(entity.getBuyerUserid());
        userMoneyLog.setPayType(entity.getPayType());
        userMoneyLog.setRemark("(挂售)订单编号："+entity.getOrdinal());
        boolean insert = userMoneyLog.insert();
        if (!insert){
            throw new UnsupportedOperationException("金额记录出现问题");
            //return ResponseData.error("金额记录出现问题");
        }
        return ResponseData.success(200,"成功",null);
    }

    public List<UserPay> queryAll(Long userid){
        return userPayService.queryAll1(userid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class,timeout = 360)
    public ResponseData editData(String ids, Integer type, String remarks) {
        if (ids == null ||type==null){
            return ResponseData.error("参数错误");
        }
        String idlist[]=ids.split(",");
        if (idlist.length==0){
            return ResponseData.error("未选中数据！");
        }
        List idList = new ArrayList();
        for (int i = 0 ; i < idlist.length;i++){
            Long s = Long.parseLong(idlist[i]);
            idList.add(s);
        }
        List<SysSell> sysSellList = baseMapper.selectBatchIds(idList);
        if (sysSellList==null||sysSellList.size()==0){
            return ResponseData.error("没有查询到相关数据！");
        }

        int stuats=0;
        if (type==1){
            stuats=2;
            remarks="同意";
        }

        List<ContractSetting> contractSettings = contractSettingService.list(new QueryWrapper<ContractSetting>()
                .in("contract_type",1,2,3));
        if (contractSettings==null||contractSettings.size()<1){
            return ResponseData.error("异常错误");
        }
        for (SysSell sysSell:sysSellList){
            sysSell.setStuats(stuats+"");
            sysSell.setStandby3(remarks);
            if (stuats==2){
                for (ContractSetting contractSetting : contractSettings){
                    Long price = contractSetting.getPrice();
                    Long price1 = contractSetting.getPrice1();
                    if (sysSell.getPrice()>price&&sysSell.getPrice()*100<price1){
                        sysSell.setContractType(contractSetting.getContractType());
                    }
                }
            }
        }  
        
        boolean b = this.updateBatchById(sysSellList);
        if (!b){
            return ResponseData.error("修改失败！");
        }
        if (stuats == 0){
            sysSellHandler.userMoneyHander(sysSellList);
        }
        sysSellHandler.sellLogAdd(sysSellList);
        return ResponseData.success();
    }

    @Override
    public ResponseData lookcnt(int pageNo,int pageSize,Integer contractType) {
        if (contractType==null){
            return ResponseData.error("参数错误！");
        }
        ContractSetting contract = contractSettingService.getOne(new QueryWrapper<ContractSetting>().eq("contract_type", contractType));
        QueryWrapper<SysSell> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("contract_type",contractType);
        queryWrapper.eq("stuats","2");
        queryWrapper.orderByAsc("create_time");
        IPage<SysSell> sysSellList = baseMapper.selectPage(new Page<>(pageNo,pageSize),queryWrapper);

        return sysSellList.getTotal() > 0 ?ResponseData.success(200,"成功",sysSellList):ResponseData.error("暂无数据");
    }

    @Override
    @Transactional(rollbackFor = Exception.class,timeout = 360)
    public ResponseData appBuy(Long userid, String ordinal) {
        if(userid == null || StringUtils.isEmpty(ordinal)){
            return ResponseData.error("参数错误");
        }
        SysUser user = sysUserService.getById(userid);
        if (user == null){
          return ResponseData.error("没有该用户");
        }
        ResponseData active = isActive(user);
        if (active != null){
            return active;
        }
        if ("1".equals(user.getBackup2())){
            return ResponseData.error("该账户不可买入！请联系客服");
        }

        SysSell sysSell = baseMapper.selectOne(new QueryWrapper<SysSell>().eq("ordinal", ordinal)
                .eq("stuats","2"));
        if (sysSell==null){
            return ResponseData.error("订单出现问题请重新买入！");
        }
        if (sysSell.getBuyerUserid().equals(userid)){
            return ResponseData.error("自己不能购买自己的挂售！");
        }
        if(sysSell.getContractType()> 0 &&user.getIsNewbie() == 1){
            return ResponseData.error("您还是新手，只能购买新手合约！");
        }
        if (sysSell.getContractType()!=null&&sysSell.getContractType()== 0 &&user.getIsNewbie() != 1){
            return ResponseData.error("新手合约只能购买一次！");
        }
        if(user.getIsNewbie() == 1){
            List<SysSell> sysSellList = baseMapper.selectList(new QueryWrapper<SysSell>().eq("seller_userid",user.getId()).gt("stuats","2"));
            if (sysSellList.size()>0){
                return ResponseData.error("新手合约只能购买一次！");
            }
        }
        List<SysSell> sysSellList = baseMapper.selectList(new QueryWrapper<SysSell>().eq("seller_userid",user.getId()).ge("stuats","3").lt("stuats","5"));
        if (sysSellList.size()>2){
            return ResponseData.error("请完成前三单！");
        }
        SysSellSetting settings = sysSellSettingService.getOne(null);

        if (settings == null){
            return ResponseData.error("相关设置出现问题！");
        }
        Long time = settings.getOverTime() / 60 / 60;
        Date date = DateUtils.addDateMinut(new Date(), time.intValue());

        if ("1".equals(sysSell.getStandby1())){
            List<Payee> list = payeeService.queryAll1();
            if(list.size() == 0){
                return ResponseData.error("平台收款信息没有上传");
            }
            String pay = JSONObject.toJSONString(list);
            sysSell.setSellDetails(pay);
        }else {
            List<UserPay> payList = queryAll(sysSell.getBuyerUserid());
            //List<UserPay> payList = userPayMapper.list(new QueryWrapper<UserPay>().eq("userid", sysSell.getBuyerUserid()));
            if(payList == null) {
                return ResponseData.error("暂无收账信息");
            }
            String pay = JSONObject.toJSONString(payList);
            sysSell.setSellDetails(pay);
        }

        sysSell.setPayTime(date);
        sysSell.setStuats("3");
        sysSell.setSellerUserid(userid);
        int version = sysSell.getVersion();
        sysSell.setVersion(sysSell.getVersion()+1);
        int update = baseMapper.update(sysSell, new QueryWrapper<SysSell>().eq("stuats", "2").
                eq("version", version).eq("id",sysSell.getId()));
        if (update<1){
            return ResponseData.error("订单已被购买！");
        }
        sysSellHandler.payQueue(sysSell,settings.getOverTime());
        return ResponseData.success(200,"买入成功！",null);
    }

    @Override
    public ResponseData appContractDetail(Long userid, String ordinal) {

        if (userid == null || StringUtils.isEmpty(ordinal)){
            return ResponseData.error("参数错误！");
        }
        //订单模块
        SysSell sysSell = baseMapper.selectOne(new QueryWrapper<SysSell>().eq("ordinal", ordinal));
        if (sysSell==null){
            return ResponseData.error("合约已丢失！");
        }
        return ResponseData.success(200,"成功",sysSell);
    }
    //买方状态查询
    @Override
    public ResponseData appSellCheckPayment(Long userid, String stuats) {
        if (userid == null || StringUtils.isEmpty(stuats)){
            return ResponseData.error("参数错误！");
        }
        //订单模块
        List<SysSell> sysSell = baseMapper.selectList(new QueryWrapper<SysSell>().eq("stuats", stuats).eq("seller_userid",userid).orderByDesc("create_time"));
        if (sysSell==null||sysSell.size()==0){
            return ResponseData.error("暂无数据！");
        }
        return ResponseData.success(200,"成功",sysSell);
    }

    //卖方状态查询
    @Override
    public ResponseData appBuyCheckPayment(Long userid, String stuats) {
        if (userid == null || StringUtils.isEmpty(stuats)){
            return ResponseData.error("参数错误！");
        }
        QueryWrapper<SysSell> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("buyer_userid",userid);
        if ("2".equals(stuats)){
            queryWrapper.in("stuats", "1","2");
        }else {
            queryWrapper.eq("stuats", stuats);
        }
        queryWrapper.orderByDesc("create_time");
        //订单模块
        List<SysSell>  sysSell= baseMapper.selectList(queryWrapper);
        if (sysSell==null||sysSell.size()==0){
            return ResponseData.error("暂无数据！");
        }
        return ResponseData.success(200,"成功",sysSell);
    }


    @Override
    @Transactional(rollbackFor = Exception.class,timeout = 360)
    public ResponseData appPay(SysSell sysSell) {
        String ordinal = sysSell.getOrdinal();
        String payDetails = sysSell.getPayDetails();
        if (StringUtils.isEmpty(ordinal) ||StringUtils.isEmpty(payDetails)){
            return ResponseData.error("参数错误！");
        }
        SysSell sysSell1 = baseMapper.selectOne(new QueryWrapper<SysSell>().eq("ordinal", ordinal).eq("stuats","3"));
        if (sysSell1 == null){
            return ResponseData.error("该订单出现错误！");
        }
        SysSellSetting settings = sysSellSettingService.getOne(null);

        if (settings == null){
            return ResponseData.error("相关设置出现问题！");
        }
        Long time = settings.getStandby2() / 60 / 60;
        Date date = DateUtils.addDateMinut(new Date(), time.intValue());
        sysSell1.setAffirmTime(date);
        sysSell1.setPayTime(new Date());
        sysSell1.setPayDetails(payDetails);
        sysSell1.setPayRemark(sysSell.getPayRemark());
        sysSell1.setStuats("4");
        int version = sysSell1.getVersion();
        sysSell1.setVersion(version+1);
        int update = baseMapper.update(sysSell1, new QueryWrapper<SysSell>().
                eq("id", sysSell1.getId()).eq("version", version));
        if (update<1){
            return ResponseData.error("该订单支付失败！");
        }

        sysSellHandler.affirmQueue(sysSell1,settings.getStandby2());

        return ResponseData.success(200,"支付成功！",null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class,timeout = 360)
    public ResponseData appAffirm(String ordinal,Long userid ) {
        if (StringUtils.isEmpty(ordinal)||userid==null){
            return ResponseData.error("参数错误");
        }
        SysSell sysSell = baseMapper.selectOne(new QueryWrapper<SysSell>().eq("ordinal", ordinal).eq("stuats","4").eq("buyer_userid",userid));
        if (sysSell == null){
            return ResponseData.error("该订单出现错误！");
        }

        ResponseData responseData=null;
        try {
             responseData = sysSellHandler.affirmOrder(sysSell);
        }catch (Exception e){
            e.printStackTrace();
        }

        return responseData == null ? ResponseData.error("异常错误") : responseData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class,timeout = 360)
    public ResponseData appComplain(String ordinal, Long userid,String phone,String title,String complainDetails) {
        if (StringUtils.isEmpty(ordinal)||userid==null||StringUtils.isEmpty(phone)||StringUtils.isEmpty(title)){
            return ResponseData.error("参数错误");
        }
        SysSell sysSell = baseMapper.selectOne(new QueryWrapper<SysSell>().eq("ordinal", ordinal).eq("stuats","4").eq("buyer_userid",userid));
        if (sysSell == null){
            return ResponseData.error("该订单出现错误！");
        }
        sysSell.setStuats("6");
        sysSell.setTitle(title);
        sysSell.setAppealTime(new Date());
        sysSell.setComplainDetails(complainDetails);
        sysSell.setPhone(Long.valueOf(phone));
        int version = sysSell.getVersion();
        sysSell.setVersion(version+1);
        int update = baseMapper.update(sysSell, new QueryWrapper<SysSell>().eq("id", sysSell.getId()).eq("version", version));
        if (update<1){
           return ResponseData.error("更新错误！");
        }
        sysSellHandler.ssMsg(sysSell);
        return ResponseData.success(200,"成功",null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class,timeout = 360)
    public ResponseData platformApproval(String ordinal, Integer type, String remark) {
        if (StringUtils.isEmpty(ordinal)||type == null ){
            return ResponseData.error("参数错误");
        }
        SysSell sysSell = baseMapper.selectOne(new QueryWrapper<SysSell>().eq("ordinal", ordinal).eq("stuats","6"));
        sysSell.setAppealRemark(remark);
        ResponseData responseData=null;
        //1 申诉成功
        //2 驳回
        //3 协商成功
        if (type ==1){
            ResponseData responseData1 = platformRollback(sysSell);
            int i = baseMapper.deleteById(sysSell.getId());
            if (i<1){
                return ResponseData.error("操作错误！订单已丢失");
            }
            return responseData1;
        }
        if (type==2||type==3){
            try {
                responseData = sysSellHandler.affirmOrder(sysSell);
            }catch (Exception e){
                e.printStackTrace();
            }

            return responseData == null ? ResponseData.error("异常错误") : responseData;
        }
        return ResponseData.error("数据异常！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class,timeout = 360)
    public ResponseData unshelve(Long id) {
        if (id==null){
            return ResponseData.error("参数错误！");
        }
        SysSell sysSell = baseMapper.selectById(id);
        if (sysSell==null){
            return ResponseData.error("未找到该订单！");
        }
        int i = baseMapper.deleteById(sysSell.getId());

        return i<0? ResponseData.error("下架失败！"):ResponseData.success();
    }

    @Override
    public ResponseData refuse(String ordinal, Long userid) {
        SysSell sysSell = baseMapper.selectOne(new QueryWrapper<SysSell>().eq("ordinal", ordinal).eq("stuats","4").eq("buyer_userid",userid));
        sysSell.setStuats ( "2" );
        sysSell.setSellerUserid ( null );
        sysSell.setPayDetails ( null );
        sysSell.setPayRemark ( null );
        sysSell.setSellDetails (null);
        int version = sysSell.getVersion();
        sysSell.setVersion(version+1);
        int update = baseMapper.update(sysSell, new QueryWrapper<SysSell>().eq("id", sysSell.getId()).eq("version", version));
        return update<0? ResponseData.success():ResponseData.error("拒绝失败！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class,timeout = 360)
    public void delete(SysSellParam param){
        this.removeById(getKey(param));
    }

    @Override
    @Transactional(rollbackFor = Exception.class,timeout = 360)
    public void update(SysSellParam param){
        SysSell oldEntity = getOldEntity(param);
        SysSell newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public SysSellResult findBySpec(SysSellParam param){
        return null;
    }

    @Override
    public List<SysSellResult> findListBySpec(SysSellParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(SysSellParam param){
        Page pageContext = getPageContext();
        System.err.println(param.getContractType());
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(SysSellParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private SysSell getOldEntity(SysSellParam param) {
        return this.getById(getKey(param));
    }


    private SysSell getEntity(SysSellParam param) {
        SysSell entity = new SysSell();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    private ResponseData isActive(SysUser user){

        if ("2".equals(user.getStatus())){
            return ResponseData.error("您的账户已被冻结请联系客服！");
        }
        if (user.getAuthenticationId()==0){
            return ResponseData.error("您还没有实名认证！");
        }
        if ("0".equals(user.getBackup1())){
            return ResponseData.error("您还没有收款信息！");
        }
        return null;
    }
    /**
     * @description :返利
     * @param sysSell
     * @param money
     * @param type
     * @date : 2019/12/16 15:49
     * @author : jj
     */
    private void setSysRebate(SysSell sysSell,long money,int type,long userid){
        SysRebate sysRebate=new SysRebate();
        sysRebate.setUserid(userid);
        sysRebate.setMoney(money);
        sysRebate.setOrdinal(sysSell.getOrdinal());
        sysRebate.setRebateType(type);
        sysRebate.setCreateTime(new Date());
        sysRebateService.save(sysRebate);

    }
    /**
     * @description :申诉成功回退
     * @param sysSell
     * @date : 2019/12/16 15:49
     * @author : jj
     */
    private ResponseData platformRollback(SysSell sysSell){
        Integer payType = sysSell.getPayType();
        UserMoney userMoney = userMoneyService.getOne(new QueryWrapper<UserMoney>().eq("userid", sysSell.getBuyerUserid()));
        if (userMoney==null){
            return ResponseData.error("没有该用户");
        }
        //可用金额
        if (payType==0){
            userMoney.setAvailMoney(userMoney.getAvailMoney()+sysSell.getPrice());
        }
        //团队返利金额
        if (payType==1){
            userMoney.setExpandMoney(userMoney.getExpandMoney()+sysSell.getPrice());
        }
        //推广金额
        if (payType==2){
            userMoney.setRebateMoney(userMoney.getRebateMoney()+sysSell.getPrice());
        }
        long version = userMoney.getVersion();
        userMoney.setVersion(version+1);
        boolean update = userMoneyService.update(userMoney, new QueryWrapper<UserMoney>().eq("id", userMoney.getId()).eq("version", version));

        if (!update){
            throw new UnsupportedOperationException("金额更新异常");
        }
        UserMoneyLog userMoneyLog=new UserMoneyLog();
        userMoneyLog.setMoney(sysSell.getPrice());
        userMoneyLog.setPayType(payType);
        userMoneyLog.setRemark("申诉金额回退！");
        boolean save = userMoneyLogService.save(userMoneyLog);
        if (!save){
            throw new UnsupportedOperationException("金额回退异常");
        }
        return  ResponseData.success(200,"成功",null);
    }

    /**
     * 获得当天零时零分零秒
     * @return
     */
    private Date initDateByDay(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    public void upSell() {
        Date now = new Date();
        Date date = new Date(now.getTime() - 180000);
        List<SysSell> sysSells = this.baseMapper.selectList(new QueryWrapper<SysSell>().lt("affirm_time", date).eq("stuats", 4));
        if(sysSells.size() > 0){
            sysSells.forEach(x -> {
                ResponseData responseData = sysSellHandler.affirmOrder(x);
            });
        }
    }

    public void upIndent() {
        Date now = new Date();
        Date date = new Date(now.getTime() - 180000);
        List<SysSell> sysSells = this.baseMapper.selectList(new QueryWrapper<SysSell>().lt("pay_time", date).eq("stuats", 3));
        if(sysSells.size() > 0){
            sysSells.forEach(x -> {
                sysSellHandler.payErrorHandler(x.getId());
            });
        }
    }
}
